package vapu.examples.rmi;

import jass.engine.BufferNotAvailableException;
import jass.engine.SinkIsFullException;
import im.composer.audio.engine.Source;
import im.composer.vapu.VAPU;

public class Limiter extends VAPU {

	private float lower = 0;
	private float upper = 1;

	@Override
	public synchronized Object addSource(Source s, boolean p) throws SinkIsFullException {
		if (!getSources().isEmpty()) {
			throw new SinkIsFullException();
		}
		return super.addSource(s, p);
	}

	public void setUpper(float upper) {
		if(upper<0||upper>1||upper<lower){
			throw new IllegalArgumentException();
		}
		this.upper = upper;
	}

	public float getLower() {
		return lower;
	}

	public void setLower(float lower) {
		if(lower<0||lower>1||lower>upper){
			throw new IllegalArgumentException();
		}
		this.lower = lower;
	}

	public float getUpper() {
		return upper;
	}

	@Override
	protected void executeCommand(long timeStamp, String command) {
		// TODO Auto-generated method stub

	}

	@Override
	protected void computeBuffer() {

		try {
			float[][] inputs = getSources().get(0).getBuffer().getAllChannels();
			float[][] outputs = buf.getAllChannels();
			for(int i=0;i<inputs.length;i++){
				for(int j=0;j<bufferSize;j++){
					float f = inputs[i][j];
					boolean neg = f < 0;
					f *= neg?-1:1;
					if(f<lower){
						f=0;
					}else if(f>upper){
						f = upper;
					}
					f *= neg?-1:1;
					outputs[i][j] = f;
				}
			}
		} catch (BufferNotAvailableException e) {
		}
	}

}
